package com.dbumama.market.web.mobile.verified.controller;

import com.alibaba.fastjson.JSONObject;
import com.dbumama.market.model.BuyerUser;
import com.dbumama.market.model.Message;
import com.dbumama.market.model.UnionFit;
import com.dbumama.market.model.VerifiedInfo;
import com.dbumama.market.service.api.unionfit.UnionFitService;
import com.dbumama.market.service.api.user.UserService;
import com.dbumama.market.service.api.verified.VerifiedService;
import com.dbumama.market.web.core.annotation.RouteBind;
import com.dbumama.market.web.core.controller.BaseMobileController;
import com.dbumama.market.web.core.plugin.spring.Inject.BY_NAME;
import com.dbumama.market.web.core.utils.AjaxResult;
import com.dbumama.market.web.core.utils.DateUtil;
import com.dbumama.market.web.core.utils.FacePlusPlus;
import com.dbumama.market.web.core.utils.RegexUtils;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;
import org.apache.commons.io.FileUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RouteBind(path = "verified")
public class VerifiedController extends BaseMobileController{

	@BY_NAME
	UnionFitService unionFitService;
	@BY_NAME
	VerifiedService verifiedService;
	@BY_NAME
	UserService userService;

	AjaxResult result = new AjaxResult();

	public void index(){
		BuyerUser user = userService.findById(getBuyerId());
		if("0".equals(user.getStatus())){
			render("/verified/verified.html");
		}else{
			VerifiedInfo verifiedInfo = verifiedService.findByBuyerId(getBuyerId());
			setAttr("idNum",verifiedInfo.getIdNum());
			setAttr("name",verifiedInfo.getName());
			render("/verified/verifiedInfo.html");
		}
	}

	public void verified(){
		try{
			String idnumber = getPara("idnumber");
			String name = getPara("name");
			String validdate = getPara("validdate");
			String idcard_authority = getPara("idcard_authority");
			//照片地址
			String idZImgPath = getPara("frontUrlz");
			String idFImgPath = getPara("frontUrlf");
			if(StringUtils.isEmpty(idnumber) || !RegexUtils.find(RegexUtils.ID_CARD, idnumber)){
				log.debug("check idnumber["+RegexUtils.encodeIdCard(idnumber)+"] is empty and is regex");
				result.addError("身份证号填写不规范");
				renderJson(result);
				return;
			}

			VerifiedInfo verifiedInfo = verifiedService.findByIdNum(idnumber);
			if(verifiedInfo != null){
				result.addError("此身份证已被注册");
				renderJson(result);
				return;
			}

			Map<String,String> parmMap = new HashMap<String,String>();
			parmMap.put("idnumber", idnumber);
			parmMap.put("name", name);
			parmMap.put("validdate", validdate);
			parmMap.put("idcard_authority", idcard_authority);
			parmMap.put(getBuyerId()+"z", idZImgPath);
			parmMap.put(getBuyerId()+"f", idFImgPath);

			boolean flag = insertVerifiedInfo(parmMap);


			String msg = "实名认证成功";
			if(flag){
				boolean insertFlag = insertMessage(msg);
				log.info("---------------insert message result:["+flag+"]-------------------------");
				result.success("实名认证成功");
			}else{
				msg = "实名认证失败";
				boolean insertFlag = insertMessage(msg);
				log.info("---------------insert message result:["+flag+"]-------------------------");
				result.addError("实名认证失败");
			}
			renderJson(result);
		}catch (Exception e){
			log.error("verified error",e);
			result.addError("系统繁忙，请稍后再试");
			renderJson(result);
		}
	}

	public boolean insertVerifiedInfo(Map<String, String> parmMap) {
		try{
			VerifiedInfo verifiedInfo = new VerifiedInfo();
			verifiedInfo.setBuyerId(getBuyerId());
			verifiedInfo.setMobile(getBuyerUser().getPhone());
			verifiedInfo.setIdNum(parmMap.get("idnumber"));
			verifiedInfo.setName(parmMap.get("name"));
			verifiedInfo.setIdcardAuthority(parmMap.get("idcard_authority"));
			verifiedInfo.setValiddate(parmMap.get("validdate"));
			verifiedInfo.setFrontIdImg(parmMap.get(getBuyerId()+"z"));
			verifiedInfo.setBackIdImg(parmMap.get(getBuyerId()+"f"));
			verifiedInfo.setCreated(new Date());
			verifiedInfo.setUpdated(new Date());
			boolean flag = verifiedInfo.save();
			BuyerUser user = getBuyerUser();
			user.setStatus("1");
			flag = user.update();
			return flag;
		}catch (Exception e){
			log.error("insert verified_info error",e);
			return false;
		}
	}

	public boolean insertMessage(String msg){
		try {
			Message message = new Message();
			message.setBuyerId(String.valueOf(getBuyerId()));
			message.setMsgType("1");
			message.setMsgTip(msg);
			message.setMsgDes(msg);
			message.setMsgRead("0");
			message.setMsgDate(new Date());
			boolean flag = message.save();
			return flag;
		} catch (Exception e) {
			log.error("insert message failed", e);
			return false;
		}
	}

	/**
	 * 省份证银行卡ocr
	 */
	public synchronized void uploadImgCheck(){

		log.info("--------->uploadImg_start -------------------------------------");

		JSONObject json = new JSONObject();
		Date date = new Date();
		String strDate = new SimpleDateFormat("yyyyMMdd").format(date);
		int maxfile = 10 * 1024 * 1024;

		String operator_id = String.valueOf(getBuyerId());

		String uploadFlag = null;

		try{

			UploadFile uploadfilez = getFile("imgsilz","/temp/"+strDate,maxfile, "UTF-8");
			UploadFile uploadfilef = getFile("imgsilf","/temp/"+strDate,maxfile, "UTF-8");
			UploadFile uploadfiley = getFile("imgsily","/temp/"+strDate,maxfile, "UTF-8");
			UploadFile uploadfilerz = getFile("imgsilrz","/temp/"+strDate,maxfile, "UTF-8");

			UploadFile uploadfile = null;

			if(uploadfilez != null){
				uploadFlag = "z";
				uploadfile = uploadfilez;
			}
			if(uploadfilef != null){
				uploadFlag = "f";
				uploadfile = uploadfilef;
			}
			if(uploadfiley != null){
				uploadFlag = "y";
				uploadfile = uploadfiley;
			}
			if(uploadfilerz != null){
				uploadFlag = "rz";
				uploadfile = uploadfilerz;
			}

			log.info("--------->buyerUser["+getBuyerUser().getPhone()+"]  uploadFlag["+uploadFlag+"] img");

			if(null == uploadfile){
				log.info("--------->buyerUser["+getBuyerUser().getPhone()+"]  uploadfile faild");
				json.put("error", 1);
				json.put("message", "获取上传文件失败，请输入相关信息");
			}else{
				File f = uploadfile.getFile();

				/*Long maxfileLength = Long.valueOf("2097152");
				if(f.length() >= maxfileLength){
					log.info("--------->operator_name["+getLogin().getStr("operator_name")+"]  uploadFlag["+uploadFlag+"] img maxLength to long");
					json.put("error", 1);
		            json.put("message", "上传图片文件太大，请输入相关信息");
		            log.debug("--------->uploadImg_end return to html --> ["+json.toString()+"]");
		            render(new JsonRender(json.toString()).forIE());
		            return;
				}*/

				StringBuffer fileName = new StringBuffer();
				String imgSrc = null;
				if("rz".equals(uploadFlag)){
					imgSrc = DateUtil.formatCurrDateTime(DateUtil.DF_YMDHMS)+uploadFlag+getFileExt(uploadfile.getFileName());
					//,/boqi/image/cardauth/operatorid/201705.jpg
					fileName.append("/boqi/image/"+operator_id+"/cardauth/")
							.append(imgSrc);
				}else{
					imgSrc = operator_id+uploadFlag+getFileExt(uploadfile.getFileName());
					//图片文件命名格式为：operator_id+(z,f,y) z表示为身份证面，f为身份证反面，y为银行卡正面，rz为银行卡认证
					//,,/boqi/image/verified/operatorid/operator_id+(z,f,y,rz).jpg
					fileName.append("/boqi/image/"+operator_id+"/verified/")
							.append(imgSrc);
					//String fileName="/upload/verified/" +operator_id+"/"+operator_id+uploadFlag+getFileExt(uploadfile.getFileName());
				}

				String imgPath = fileName.toString();

				File newFile = new File(imgPath);

				if(newFile.exists()){
					log.info("--------->buyerUser["+getBuyerUser().getPhone()+"]  uploadFlag["+uploadFlag+"] img delete result["+newFile.delete()+"]");
				}

				FileUtils.copyFile(f,newFile);

				if(f.exists()){
					f.delete();
				}

				imgPath = newFile.getAbsolutePath();



				//缓存session
				setSessionAttr(operator_id+uploadFlag,fileName.toString());

				log.info("buyerUser["+getBuyerUser().getPhone()+"]  uploadFlag["+uploadFlag+"]img return to html---->src["+imgSrc+"]");

				json.put("src", imgSrc);

				JSONObject result = null;

				if("z".equals(uploadFlag) || "f".contentEquals(uploadFlag)){
					//调用身份证接口
					result = new FacePlusPlus().getIdCardInfo(imgPath);
				}else if("y".equals(uploadFlag) || "rz".equals(uploadFlag)){
					//调用银行卡识别接口
					result = new FacePlusPlus().getBankCardInfo(imgPath);
					//result = new JSONObject();
//				result.put("cardno", "6226900206533131");
//				result.put("bankname", "中信银行");
				}

				//后期图片信息
//				result = new JSONObject();
//				result.put("name", "张三");
//				result.put("idnumber", "431126198804839980");
//				result.put("authority", "江苏省南京市");
//				result.put("validdate", "2017.08.08-2027.08.08");
//				result.put("cardno", "6226900206533131");
//				result.put("bankname", "中国农业银行");

				if(!StringUtils.isEmpty(result)){

					json.put("error", 1);
					json.put("message", "上传图片失败，请输入相关信息");

					if("z".equals(uploadFlag)){
						//判断身份证正面
						String strName = result.getString("name");
						String strIdnumber = result.getString("id_card_number");

						if(!StringUtils.isEmpty(strName) && !"null".equals(strName)
								&& !StringUtils.isEmpty(strIdnumber) && !"null".equals(strIdnumber)){

							json.put("name", strName);
							json.put("idnumber", strIdnumber);
							json.put("error", 0);
							json.put("message", "上传身份证正面图片成功");
						}
					}else if("f".equals(uploadFlag)){
						//判断身份证反面
						String strAuthority = result.getString("issued_by");//公安局发行地址
						String strValiddate = result.getString("valid_date");//有效期

						if(!StringUtils.isEmpty(strValiddate) && !"null".equals(strValiddate)){
							json.put("authority", strAuthority);
							json.put("validdate", strValiddate);
							json.put("error", 0);
							json.put("message", "上传身份证反面图片成功");
						}
					}else if("y".equals(uploadFlag) || "rz".equals(uploadFlag)){

						//判断银行卡号
						String strCardNo = result.getString("cardno");
						String strBankName = result.getString("bankname");
						//json.put("cardno", strCardNo);

						if(!StringUtils.isEmpty(strCardNo) && !"null".equals(strCardNo)){

							json.put("bankname", strBankName.substring(0,strBankName.indexOf('行')+1));
							json.put("error", 0);
							//苹果浏览器会对卡号做脱敏处理导致ajax请求失败，故在卡号前面添加X字符
							json.put("cardno", "X"+result.getString("cardno"));
							json.put("message", "上传银行卡正面图片成功");

							//TODO 检测是否为借记卡[代码暂定]
							if("y".equals(uploadFlag) && null == checkCardBin(strCardNo,"1")){
								json.put("error", 1);
								json.put("message", "请上传借记卡或储蓄卡正面照片");
							}
						}
					}
				}else{
					json.put("error", 1);
					json.put("message", "获取照片信息失败，请输入相关信息");
				}
			}
		}catch(Exception e){
			//清楚session缓存
			if(!StringUtils.isEmpty(operator_id) && !StringUtils.isEmpty(uploadFlag)){
				removeSessionAttr(operator_id+uploadFlag);
			}

			e.printStackTrace();
			json.put("error", 1);
			json.put("message", e.getMessage()==null?"上传文件出错，请输入相关信息":e.getMessage());
		}

		log.debug("--------->uploadImg_end return to html --> ["+json.toString()+"]");
		System.out.println("uploadImg................");
/*		json.put("error", 1);
		json.put("message", "上传文件出错，请输入相关信息Test");*/
		render(new JsonRender(json.toString()).forIE());
	}

	public void getImg() {
		try {
			String name = getPara("path");
			File file = new File("/boqi/image/" + getBuyerUser().getId() + "/" + name);
			this.renderFile(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取文件后缀
	 * @param @param fileName
	 * @param @return 设定文件
	 * @return String 返回类型
	 */
	public static String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf('.'), fileName.length());
	}

	/**
	 * 检测是否为借记卡
	 *
	 * @param cardNo
	 * @param cardTypeFlag 卡种
	 *                     1：借记卡
	 *                     2：贷记卡
	 *                     3：准贷记卡
	 *                     4：预付费卡
	 * @return
	 */
	public UnionFit checkCardBin(String cardNo, String cardTypeFlag) {
		log.debug("checkCardbin_start parm:cardNo[" + cardNo + "] cardTypeFlag[" + cardTypeFlag + "]");
		UnionFit union = null;
		try {
			cardNo = cardNo.replaceAll(" ", "");
			log.debug("cardNo.replaceAll result cardNo[" + cardNo + "]");
			List<UnionFit> unionFitList = CacheKit.get("forever", "unionFit");
			if (unionFitList == null || unionFitList.isEmpty()) {
				unionFitList = unionFitService.getUnionFitAll();
				CacheKit.put("forever", "unionFit", unionFitList);
			}
			log.debug("unionFitList.size[" + unionFitList.size() + "]");
			for (UnionFit unionFit : unionFitList) {
				String cardCtt = unionFit.getStr("BINCTT");
				String cardNoctt = cardNo.substring(0, Integer.parseInt(unionFit.getStr("BINLEN")));
				if (cardCtt.equals(cardNoctt)) {
					log.debug("unionFit: cardCtt[" + cardCtt + "]  cardNo.substring(0,cardCtt.length())=[" + cardNoctt + "]  cardCtt.equals(cardNoctt)=[" + cardCtt.equals(cardNoctt) + "]");
					union = unionFit;
					break;
				}
			}
			log.debug("union checkNull [" + union + "]");
			if (null != union) {
				String cardType = union.getStr("DCFLAG");
				log.debug("union cardType [" + cardType + "]");
				if (!StringUtils.isEmpty(cardType) && cardTypeFlag.equals(cardType)) {
					log.debug("checkCardbin_end return true");
					return union;
				}
			}
		} catch (Exception e) {
			log.error("checkCardBin Exception",e);
		}
		log.debug("checkCardbin_end return null");
		return null;
	}


}
